import {View, Text} from '@tarojs/components'
import Taro, {getStorageSync, redirectTo, reLaunch, setStorageSync, showToast, useLoad} from '@tarojs/taro'
import './index.scss'
import { Button,Checkbox,Image } from '@nutui/nutui-react-taro'
import React, {useState} from "react";
import UserService from '@/shared/services/user/user.service'
import {loadingService} from "@/shared/utils/loading";

export default function Login () {

  const [check,setCheck] = useState<boolean>(false)
  const [showAuthButton, setShowAuthButton] = useState<boolean>(false)

  console.log('check value:', check, 'type:', typeof check);

  useLoad(() => {
    console.log('Page loaded.')
  })

  const handleLoginClick = (check: Boolean = false) => {
    setCheck(check)
    if (!check) {
      showToast({
        title: '请先阅读并同意协议',
        icon: 'none'
      })
      setShowAuthButton(false)
      return
    }

    // 先显示授权按钮
    setShowAuthButton(true)
  }

  const handleGetPhoneNumber = async (res) => {
    console.log(res.detail,"请求电话回调")
    console.log(res.detail.code,"请求电话回调")

    if(!res.detail.code) return

    const { code } = await Taro.login();
    loadingService.show({})
    const response = await UserService.wxLogin({
      code: code,
      phoneCode: res.detail.code,
      debug: false
    })

    loadingService.hide()
    if(response.code == 0){
      console.log("redirectTo({ url: '/pages/index/index' })")
      setStorageSync('token',response.data.accessToken)
      reLaunch({ url: '/pages/index/index' })
    }else{
      console.log(`wxLogin error ${response.code}`)
    }
    console.log(response)

  }
  const userProtocol = () => {
    Taro.navigateTo({
      url: `/pages/webview/index?src=https://www.xiliyulifa.com/yhxy`
    })
  }

  const ysProtocol = () => {
    Taro.navigateTo({
      url: `/pages/webview/index?src=https://www.xiliyulifa.com/ysxy`
    })
  }

  const backHome = () => {
    const pages = Taro.getCurrentPages()
    if (pages.length > 1) {
      // 有上一页，返回上一页
      Taro.navigateBack({
        delta: 1
      })
    } else {
      // 没有上一页，跳转到首页
      Taro.reLaunch({
        url: '/pages/index/index'
      })
    }
  }

  return (
    <View className='login'>
      {/*<Text className='back'>返回</Text>*/}

      <Text className='welcome'>欢迎贵宾光临囍理运</Text>
      <Text className='tips'>登录后可享受相关服务</Text>

      <View className="logo">
        <View className="circle">
          <Image className="logoIcon" src={require('@/assets/logo.png')} />
        </View>
      </View>
      <View className='bottom'>
        <Image
          src={require('@/assets/icon_back.png')}
          className='back'
          width={40}
          height={40}
          onClick={backHome}
        />
        {!showAuthButton ? (
          <Button
            block
            className='toLogin'
            type='primary'
            color={check ? '#121214' : '#999999'}
          >
            授权手机号登录
          </Button>
        ) : (
          /* 第二步：授权按钮获取手机号 */
          <Button
            block
            className='toLogin'
            openType='getPhoneNumber'
            onGetPhoneNumber={handleGetPhoneNumber}
            type='primary'
            color='#121214'
          >
            授权手机号登录
          </Button>
        )}

        <View className='protocol'>
          <Checkbox
            className="test"
            label="我已阅读并同意"
            checked={check}
            onChange={(val) => handleLoginClick(val)}
          />
          <Text className='secret' onClick={ysProtocol}>《隐私协议》</Text>
          <Text className="tips">,</Text>
          <Text className='user' onClick={userProtocol}>《用户协议》</Text>
          <Text></Text>
        </View>
      </View>
    </View>
  )
}
